package com.sfx.service.impl;

import com.sfx.domain.ResponseResult;
import com.sfx.domain.entity.LoginUser;
import com.sfx.domain.entity.User;
import com.sfx.domain.vo.*;
import com.sfx.enums.AppHttpCodeEnum;
import com.sfx.exception.SystemException;
import com.sfx.service.AdminLoginService;
import com.sfx.service.MenuService;
import com.sfx.service.RoleService;
import com.sfx.utils.BeanCopyUtils;
import com.sfx.utils.JwtUtil;
import com.sfx.utils.RedisCache;
import com.sfx.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.sfx.constants.RedisConstants.ADMIN_LOGIN_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-14
 * Time: 18:01
 */
@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

     @Override
    public ResponseResult login(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        if(StringUtils.isAnyBlank(userName,password)) {
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME_PASSWORD);
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null) {
            //验证失败
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }
        //验证成功
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //3.得到用户Id
        Long userId = loginUser.getUser().getId();
        //4.根据userId生成JWT
        String token = JwtUtil.createJWT(userId.toString());
        //5.保存用户信息到redis中
        redisCache.setCacheObject(ADMIN_LOGIN_KEY + userId, loginUser);
        //6.返回登陆凭证+userInfo
        AdminUserLoginVo adminUserLoginVo = new AdminUserLoginVo(token);
        return ResponseResult.okResult(adminUserLoginVo);
    }

    @Override
    public ResponseResult<AdminInfoVO> getInfo() {
        //1.获取当前登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUser().getId();
        //2.根据userId查询权限信息
        List<String> permissions = menuService.selectPermissionsByUserId(userId);
        //3.根据userId查询角色信息
        List<String> roles = roleService.selectRolesByUserId(userId);
        //4.根据userId查询用户信息
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        AdminInfoVO adminInfoVO = new AdminInfoVO(permissions,roles,userInfoVo);
        return ResponseResult.okResult(adminInfoVO);
    }

    /**
     * 返回的菜单数据需要体现父子菜单的层级关系
     * @return
     */
    @Override
    public ResponseResult getRouters() {
        //1.查看当前登陆用户的userId
        Long userId = SecurityUtils.getLoginUser().getUser().getId();
        //2.如果是管理员
        if(userId == 1L) {
            //2.1menus中需要有所有菜单类型为C或者M的，状态为正常的，未被删除的权限

        }
        //3.不是管理员,带有父子菜单的AdminRoutersVo
        List<MenuVo> menus = selectMenuById(userId);

        //4.封装menus返回

        AdminRoutersVo adminRoutersVo = new AdminRoutersVo(menus);
        return ResponseResult.okResult(adminRoutersVo);
    }

    private List<MenuVo> selectMenuById(Long userId) {
        //3.1查询菜单


        //3.2查询父子关系


        return null;
    }
}